<?php

namespace app\admin\model\goods;

use app\admin\model\Category;
use app\admin\model\UserGoodsGroup;
use app\admin\validate\Goods as val_goods;
use think\exception\ValidateException;
use think\Model;

class Goods extends Model
{
    protected $autoWriteTimestamp = 'datetime';
    protected $json = ['album','server_id_json'];
    protected $jsonAssoc = true;



    public function getStatusAttr($value)
    {
        $Status = [0=>'下架',1=>'上架'];
        return $Status[$value];
    }


    public  function GetUserGoodsGroup(){

        return $this->hasOne(Category::class,'id','cate_id');
    }
    public  function GoodsList(){

        return self::select();
    }


    public function getCategory(){
        return  $this->hasOne(Category::class,'id','cate_id')->bind(['type','cate_name'=>'name']);
    }
    /***
     * 获取列表
     */

    public static function GetGoodsList(){

        $where=[];
        $keyword=input('keyword','','trim');
        $page = !empty(input('page')) ? input('page') : 1;//默认第一页
        $limit = !empty(input('limit')) ? input('limit') : 12;//前端不传默认每页15条
        input('sort') ?$order=input('sort'):$order=['id'=>'desc'];
        !empty($keyword) &&  $where[]=['name','like','%'.$keyword.'%'];
        input('status') && $where[]=['status','=',input('status')];
        (input('start_time') && input('end_time')) &&  $where[]=['create_time','between',[input('start_time'),input('end_time')]];


        $where[]=['store_id','=',session('store_id')];
        $result=self::where($where)->with(['getCategory'])
            ->visible(['getCategory' =>['type','name']])
            ->hidden(['album','getCategory'])->order($order)->page($page)->limit($limit)->select();

        return array(
            'count'=>count($result),
            'data'=>$result
        );



        // return self::with(['GetUserInfo','GetUserGoodsGroup'])->visible(['GetUserInfo' => ['head_pic', 'username'],'GetUserGoodsGroup'=>['name']])->select();
    }

    /****
     * 用户批量上传商品
     */
    public static function EditGoods($data){


        unset($data['thumbs']);

        $data['store_id']=session('store_id');
        $data['goods_sn']='Yt_'.date('YmdHis').rand(111,999);

            try {
                validate(val_goods::class)->check($data);

            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                $infos=$e->getError();
                $msg=[
                    'code'=>$infos['code'],
                    'msg'=>$data['title'].$infos['msg']
                ];
                return $msg;
            }
        $Goods=new Goods();
        $Goods->startTrans();

        try {

            if($data['id']){
                $Goods->where(['id'=>$data['id']])->update($data);
            }else{
                $Goods->save($data);
            }

            // 提交事务
            $Goods->commit();
            $data = array(
                'code' => 200,
                'msg' => '成功啦~!',
            );
            return $data;
        } catch (\Exception $e) {
            // 回滚事务
            $Goods->rollback();
            $data = array(
                'code' => 4006,
                'msg' => $e->getMessage(),
            );
            return $data;
        }

    }

    /*****
     * 修改状态
     */
    public static function UpdateStatus(){
        $save=input('');
        unset($save['type']);
        unset($save['id']);
        if(input('type')=='group'){
            $group_id=self::where(['id'=>input('id')])->value('group_id');
            if($group_id>0){
                self::where(['group_id'=>$group_id])->update($save);
                UserGoodsGroup::where(['id'=>$group_id])->update($save);
            }else{
                self::where(['id'=>input('id')])->update($save);
            }

        }else{
            self::where(['id'=>input('id')])->update($save);
        }

        $data = array(
            'code' => 200,
            'msg' => '成功!',
        );
        return $data;

    }

    /****
     * 删除商品
     */
    public static function GoodsDel(){

        self::where(['id'=>input('id')])->delete();

        $data = array(
            'code' => 200,
            'msg' => '成功!',
        );
        return $data;
    }

    public static function GoodsDetail(){

        $group_id=self::where(['id'=>input('id')])->value('group_id');

        if($group_id>0){
            $result=self::where(['group_id'=>$group_id])->with(['getCategory','GetUserInfo'])
                ->visible(['getCategory' =>['type','name'],'GetUserInfo' => ['head_pic', 'nickname']])
                ->hidden(['file_address','getCategory'])->select();
        }else{
            $result=self::where(['id'=>input('id')])->with(['getCategory','GetUserInfo'])
                ->visible(['getCategory' =>['type','name'],'GetUserInfo' => ['head_pic', 'nickname']])
                ->hidden(['file_address','getCategory'])->find();
        }

        return ['group_id'=>$group_id,'list'=>$result];

    }

    public static function GoodsGroupDetail(){

        $result=self::where(['id'=>input('id')])->with(['getCategory','GetUserInfo'])
            ->visible(['getCategory' =>['type','name'],'GetUserInfo' => ['head_pic', 'nickname']])
            ->hidden(['file_address','getCategory'])->find();
        return $result;
    }

    public static function GetRecommendGoodsList($type){

        $where=[];
        $keyword=input('keyword','','trim');
        $id=Category::Where(['type'=>$type])->column('id');
        $page = !empty(input('page')) ? input('page') : 1;//默认第一页
        $limit = !empty(input('limit')) ? input('limit') : 12;//前端不传默认每页15条
        $type !=3 ? $where[]=['cate_id','in',$id]:false;
        $keyword ?   $where[]=['title|id','like','%'.$keyword.'%']:false;
        $where[]=['status','>',1];


        $result=self::where($where)->with(['getCategory','GetUserInfo'])
            ->visible(['getCategory' =>['type','name'],'GetUserInfo' => ['head_pic', 'nickname']])
            ->hidden(['file_address','photos','getCategory'])->select();


        $model=dataGroup($result->toArray(),'group_id');



        $data = array(
            'code' => 0,
            'msg' => '成功!',
            'count'=>!empty($keyword) ?count($model):0,
            'data'=>!empty($keyword) ?array_slice($model, ($page-1)*$limit, $limit):[],
        );
        return $data;

        // return self::with(['GetUserInfo','GetUserGoodsGroup'])->visible(['GetUserInfo' => ['head_pic', 'username'],'GetUserGoodsGroup'=>['name']])->select();
    }

    public static function UpdateGoods(){

        $data=input('post.');

        $result=self::where(['id'=>input('id')])->update($data);
        if(!$result){
            $data = array(
                'code' => 200,
                'msg' => '成功!',
            );
            return $data;
        }else{
            $data = array(
                'code' => 200,
                'msg' => '未做修改!',
            );
            return $data;
        }

    }

}